package cn.uestc.labhms.modules.hms.service.impl;

import cn.uestc.labhms.modules.hms.dao.HmsChiEngDao;
import cn.uestc.labhms.modules.hms.dao.XlsxDao;
import cn.uestc.labhms.modules.hms.entity.HmsChiEngEntity;
import cn.uestc.labhms.modules.hms.exception.HMSException;
import cn.uestc.labhms.modules.hms.service.ConditionFindService;
import cn.uestc.labhms.modules.hms.util.HMSPageUtils;
import cn.uestc.labhms.modules.hms.util.TableUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * @author Mu.tz
 */
@Service
@Slf4j
public class ConditionFindServiceImpl implements ConditionFindService {
    @Autowired
    private HmsChiEngDao hmsChiEngDao;
    @Autowired
    private XlsxDao xlsxDao;
    @Value("${hms.pageSize}")
    private Integer pageSize;

    /**
     * 根据条件查询符合的数据，按分页结果返回
     * @param keys
     * @param vals
     * @return
     */
    @Override
    public List<HMSPageUtils> getConditionTables(List<String> keys, List<String> vals, Integer curPage) {
        if (ObjectUtils.isEmpty(curPage)) {
            throw new HMSException("当前页不能为空");
        }
        if (ObjectUtils.isEmpty(keys) || ObjectUtils.isEmpty(vals)) {
            throw new HMSException("查询条件或查询值不为空");
        }
        if (keys.size() != vals.size()) {
            throw new HMSException("查询条件和查询值没有一一对应");
        }
        List<HMSPageUtils> res = new LinkedList<>();
        // 把中文字段全部换成英文字段
        List<String> keysE = new LinkedList<>();
        for (String key : keys) {
            HmsChiEngEntity hmsChiEngEntity = hmsChiEngDao.selectOne(new QueryWrapper<HmsChiEngEntity>().eq("chi_field", key).last("limit 1"));
            if (ObjectUtils.isEmpty(hmsChiEngEntity) || ObjectUtils.isEmpty(hmsChiEngEntity.getEngField())) {
                throw new HMSException("没有此查询条件，请重新检查查询条件");
            }
            keysE.add(hmsChiEngEntity.getEngField());
        }
        // 获取拥有合法查询条件的表名
        List<String> tableNames = TableUtil.getValidTableNames(keysE);
        if (ObjectUtils.isEmpty(tableNames)) {
            throw new HMSException("无满足全部条件的数据");
        }
        // 将查询条件和对应的值组装为一个map
        Map<String, String> keyValMap = TableUtil.parseData(keysE, vals);
        // 查询每张表中符合条件的记录
        for (String tableName : tableNames) {
            HMSPageUtils tableData = TableUtil.getTableData(tableName, keyValMap, curPage, pageSize);
            res.add(tableData);
        }
        return res;
    }
}
